#include "tcpclient.h"
#include "ui_tcpclient.h"

tcpclient::tcpclient(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tcpclient)
{
    ui->setupUi(this);

    tcpSocket = new QTcpSocket(this);

    connect(tcpSocket,&QTcpSocket::connected,
            [=]()
            {
                ui->textEdit_Recv->setText("成功建立连接");
                emit connectsuccess();
            }
    );

    connect(tcpSocket,&QTcpSocket::readyRead,
            [=]()
            {
                QByteArray arr = tcpSocket->readAll();
                ui->textEdit_Recv->append(arr);
                qstr = QString::fromStdString(arr.toStdString());
                emit sendsignal();
            }

    );
}

tcpclient::~tcpclient()
{
    delete ui;
}

void tcpclient::on_pushButton_Connect_clicked()
{
    QString ip = ui->lineEdit_IPAddr->text();
    qint16 port = ui->lineEdit_Port->text().toInt();

    tcpSocket->connectToHost(QHostAddress(ip),port);
}

void tcpclient::on_pushButton_Send_clicked()
{
    QString str = ui->textEdit_Send->toPlainText();
    tcpSocket->write(str.toUtf8().data());
}

void tcpclient::on_pushButton_Close_clicked()
{
    tcpSocket->disconnectFromHost();
    tcpSocket->close();
}

void tcpclient::SetSock(string ipaddr, int port) {
    this->s_port = port;
    this->s_ipaddr = QString::fromStdString(ipaddr);
}
